/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wads.com.AutoDocumentTransaction;
import wads.com.DocumentTemplateInfo;
import wads.com.UserInfo;
import wads.com.WADTools;

public class SearchAndShowSuccessRestrictDoc extends HttpServlet {
  private static final long serialVersionUID = 6287812064428692990L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  public final int USER = 1;
  public final int FULLUSER = 2;
  String app_Path;

  Vector successFile;
  Vector documentIDFile;
  Vector successFileList = new Vector();

  AutoDocumentTransaction adTran;
  DocumentTemplateInfo dtInfo;

  //List of String
  String Transaction_ID;
  String template_ID;
  String template_Name;
  String ownerName;
  String currentUser;
  String sendDate;
  String updateDate;
  String createdTime;
  String submitTime;

  ServletOutputStream sos;
  UserInfo uiRestrictUser;
  String fullNameRestrict;
  UserInfo uiPowerUser;
  HttpSession session;
  String restrictNameFromLogin;
  
  Calendar cal_ct, cal_st;
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);

    session = request.getSession(false);
    restrictNameFromLogin = (String)session.getAttribute("UserName");
    //app_Path = this.getInitParameter("app_Path");
    app_Path = WADTools.APP_PATH;
    sos = response.getOutputStream();
    //Read Beginning of HTML file to create Head of table
    this.readBeginninghtml();
    successFileList = this.listFileName();

    fullNameRestrict = getFullNameofRestrictedUser(restrictNameFromLogin);

    //filter restrict document in each power User by RestrictNameLogin
    this.fillSuccessRestrictDoc(successFileList, fullNameRestrict);

    sos.close();
  }

  /**Clean up resources*/
  public void destroy() {
  }

  public Vector listFileName(){
    Vector<String> successFile = new Vector<String>();
    File doc_Path = new File(app_Path+"res/docs/SuccessDocument/");
    if(doc_Path.isDirectory()){
      File[] listUserPath = doc_Path.listFiles();
      for(int i=0; i<listUserPath.length ;i++)
        successFile.add(listUserPath[i].getName());
    }
    return successFile;
  }

  public void readBeginninghtml(){
    File htmlFile = new File("restrict_list.html");
    String temp = null;
    byte[] buf = new byte[1024];
    boolean check = true;
    try{
        BufferedReader br = new BufferedReader(new FileReader(htmlFile));
        while((temp = br.readLine()) != null){
          if((temp.indexOf("hiddenField") == -1) && check){
            buf = temp.getBytes();
            sos.write(buf,0,temp.length());
          }else{
            check = false;
          }
        }
        br.close();
      }catch(Exception e){
        System.out.println("Exception thrown from SearchAndShowSuccessRestrictDoc.readBegininghtml()");
        e.printStackTrace();
      }
  }

  public void fillSuccessRestrictDoc(Vector successFileToShow, String RestrictName){
     //String user = null;
     String BGColor;
       for(int i=0; i<successFileToShow.size(); i++){
        //Set Color for Light Gray and Dark Gray
        if(i%2 != 0) BGColor = "#F0F0F0";
        else BGColor = "#CCCCCC";

        try{
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/SuccessDocument/" + successFileToShow.elementAt(i)));
          adTran = (AutoDocumentTransaction)ois.readObject();
          Transaction_ID = adTran.getTransaction_ID();
          template_ID = adTran.getTemplate_ID();
          template_Name = adTran.getTemplate_Name();
          //Get Full Name of User
          ownerName = this.getFullNameofRestrictedUser(adTran.getOwner_Name());
          //Get createdTime
          createdTime = this.getCreatedTime(adTran.getCreated_Date());
          sendDate = adTran.getCreated_Date().toString();
          updateDate = adTran.getCurrentTime().toString();
        if(ownerName.equals(RestrictName)){
          ObjectInputStream oisa = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/activeDocTemplate/" + template_ID + "/docTemplate.info"));
          dtInfo = (DocumentTemplateInfo)oisa.readObject();
          // String a = dtInfo.getTemplate_Name();
          String templateName = dtInfo.getTemplate_Name();
          ////add code to show document
          templateName = "<a href=servlet/show?ID=" + adTran.getTransaction_ID() + "&user=" + "SuccessDocument" + ">" + templateName + "</a>";

          String temp = " <tr bgcolor=" + BGColor + "><td width=70 align=center>" + Transaction_ID +
            "</td><td width=300>&nbsp;&nbsp;&nbsp;" + templateName +
            "</td><td width=300>&nbsp;&nbsp;&nbsp;" + ownerName +
            "</td><td width=70 align=center>" + createdTime +
            "</tr>";

          sos.write(temp.getBytes(),0,temp.length());
          oisa.close();
         }
        }catch(Exception e){
          System.out.println("Exception thrown from SearchAndShowSuccessRestrictDoc.fillSuccessRestrictDoc()");
          e.printStackTrace();
        }

     }
  }

  public String getFullNameofRestrictedUser(String name){
    String restrictUserFile = app_Path+"res/user/RestrictUser/RestrictUser.org";

    //Read Object of RestrictUser
    try{
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
      uiRestrictUser = (UserInfo)ois.readObject();
      ois.close();
    }catch(Exception e) {
      System.out.println("Exception thrown from SearchAndShowSuccessRestrictDoc.getFullNameofRestrictedUser()");
      e.printStackTrace();
    }

    if(!uiRestrictUser.isEmpty()){
       for(int i=0; i<uiRestrictUser.getSize(); i++){
          if(name.equals(uiRestrictUser.getUserDataAt(i).getUsername()))
            fullNameRestrict = uiRestrictUser.getUserDataAt(i).getName();
       }
    }
    return fullNameRestrict;
  }

  public String getCreatedTime(Date createdTime){
    cal_ct.setTime(createdTime);
    int date = cal_ct.get(Calendar.DAY_OF_MONTH);
    int month = cal_ct.get(Calendar.MONTH);
    int year = cal_ct.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }

  public String getSubmitTime(Date submitTime){
    cal_st.setTime(submitTime);
    int date = cal_st.get(Calendar.DAY_OF_MONTH);
    int month = cal_st.get(Calendar.MONTH);
    int year = cal_st.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }
}